import Vue from 'vue';
import { ref } from '@vue/composition-api'
import staticConst from "@/js/const/StaticConst.js";
import https from "@/js/https/Https.js";
import config from "@/js/conf/Config.js";
import downloadFile from "@/js/upload/DownloadFile.js";

const PAGE_SIZE = 1
// 创建一个单例状态
const state = {
    tab: ref({
        label: '门店',
        id: 'store'
    }),

    // 数据初始化 -----------------------  start  -------------------------
    store_query: ref({
        // shopid: "", //非必须 门店筛选 默认所有
        // group: "", //非必须 报表类型 1 日报 2月报 3季报  5 自定义时间的日报 默认按日统计
        time: '',
        stime: "", //非必须 自定义时间统计 开始时间 格式"2020-01-28"
        dtime: "", //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        page: 1, //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        // is_yy: 2, //预约板块1是2 否 默认否
        uid_cp: "", //成员id
        order: "1",
        pfrom: 0, //非必须 分页参数 - 页面
        pnum: staticConst.PAGE_SIZE, // 20 非必须 分页参数 - 页面显示数量
    }),

    store_shop_ls: ref([]),
    store_staff_ls: ref([]),
    store_group_ls: ref([]),
    store_order_ls: ref([]),
    store_product_ls: ref([{ value: '2', label: '按产品' }, { value: '1', label: '按服务' }]),

    store_count_ls: ref([]),
    store_loading: ref(false),
    store_hasMore: ref(true),
    store_currentId: ref(''),

    store_query_detail: ref({
        customerid: '',
        gdid: '',
        page: 1,
        pfrom: 0,
        pnum: staticConst.PAGE_SIZE,
        shopid: '',
        staffid: '',
        is_yy: '2',
    }),
    store_list: ref([]),
    store_count: ref({}),
    shop_info: ref({}),
    store_detail_loading: ref(false),
    store_detail_hasMore: ref(true),

    goods_ls: ref([]), // tab 产品列表

    is_first_init: ref(false),
    // 数据初始化 -----------------------  end  ---------------------------
}

export const useStatisticalState = () => {

    // 数据初始化 -----------------------  start  -------------------------

    // 重置参数
    const resetStoreQuery = () => {
        console.log("resetStoreQuery----")
        state.store_query.value = {
            time: '',
            stime: "",
            dtime: "",
            page: 1,
            uid_cp: "",
            order: "1",
            pfrom: 0,
            shopid: '',
        }
        state.store_query_detail.value = {
            customerid: '',
            gdid: '',
            page: 1,
            pfrom: 0,
            shopid: '',
            staffid: '',
            is_yy: '2',
        }
        state.store_list.value = []
        state.store_shop_ls.value = []
        state.store_staff_ls.value = []
        state.store_group_ls.value = []
        state.store_order_ls.value = []
        state.store_count_ls.value = []
        state.store_loading.value = false
        state.store_hasMore.value = true
        state.store_currentId.value = ''
        state.store_count.value = {}
        state.shop_info.value = {}
        state.store_detail_hasMore.value = true
    }

    const getTab = () => {
        let type = state.tab.value.id
        if (type == 'store') {
            return config.REPORT_COUNT_SHOP  // 门店
        } else if (type == 'product') {
            return config.REPORT_COUNT_GOODS // 产品
        } else if (type == 'service') {
            return config.REPORT_COUNT_GOODS // 服务 
        } else if (type == 'reserva') {
            return config.REPORT_BOOK_CUSTOMER // 预约
        } else if (type == 'customer') {
            return config.REPORT_COUNT_CUSTOM // 客户
        } else if (type == 'member') {
            return config.REPORT_COUNT_STAFF // 成员
        }
    }

    const getStoresList = async () => {
        let params = state.store_query.value;
        let type = state.tab.value.id
        if (type == 'service') {
            params.is_yy = '1'
            // params.shopid = state.store_query_detail.value.shopid
        }
        let url = getTab() // config.REPORT_COUNT_SHOP
        let res = await Vue.prototype.$api({ url: url, data: params });
        if (res.status == 1) {
            if (!res.data) {
                return;
            }
            let data = res.data;
            let result_ls = []
            if (type == 'product' || type == 'service') {
                result_ls = data?.goods_ls || []
                result_ls = result_ls.map(item => {
                    return {
                        ...item,
                        rel_img: item.imgs,
                        rel_name: item.name,
                    }
                })
            } else {
                result_ls = data?.count_ls || []
            }
            const newData = result_ls || []
            const existingTimestrs = new Set(state.store_count_ls.value.map(item => item.timestr))
            const uniqueNewData = newData.filter(item => !existingTimestrs.has(item.timestr))
            state.store_count_ls.value = state.store_count_ls.value.concat(uniqueNewData)
            state.store_hasMore.value = (result_ls && result_ls?.length) >= PAGE_SIZE
            if (state.store_query.value.page == 1) {
                state.store_currentId.value = state.store_count_ls.value[0]?.rel_id
                state.store_query_detail.value.customerid = state.store_currentId.value;
                state.store_query_detail.value.gdid = state.store_currentId.value;
                state.store_query_detail.value.shopid = state.store_currentId.value;
                state.store_query_detail.value.staffid = state.store_currentId.value;
                // 第一次渲染数据，需要从列表拿第一初始化数据
                const fristInitData = ['product', 'customer', 'member', 'service']
                if (fristInitData.includes(type)) {
                    // console.log()
                    state.shop_info.value = state.store_count_ls.value[0] || {}
                    console.log("state.shop_info.value=", state.shop_info.value)
                } else {
                    // getStoreSellLsData()
                }
                if (state.store_count_ls.value && state.store_count_ls.value.length > 0) {
                    getStoreSellLsData()
                }
            }

            // 数据初始化
            state.store_shop_ls.value = (data?.shop_ls || []).map(item => ({
                value: item.id,
                label: item.name
            }))
            state.store_shop_ls.value.unshift({
                value: '',
                label: '全部云店'
            })
            // 成员
            state.store_staff_ls.value = (data?.staff_ls || []).map(item => ({
                value: item.id,
                label: item.name
            }))
            state.store_staff_ls.value.unshift({
                value: '',
                label: '全部成员'
            })
            // 日期
            state.store_group_ls.value = (data?.mtime || []).map(item => ({
                value: item.id,
                label: item.title
            }))
            state.store_group_ls.value.unshift({
                value: '',
                label: '全部日期'
            })
            // 排序
            state.store_order_ls.value = (data?.order_ls || []).map(item => ({
                value: item.id,
                label: `按${item.title}排序`
            }))
        }
    }

    const storeLoadMoreData = () => {
        // 如果还有更多数据，则加载更多数据
        if (state.store_loading.value || !state.store_hasMore.value) {
            return
        }
        state.store_query.value.page += PAGE_SIZE
        state.store_query.value.pfrom += staticConst.PAGE_SIZE
        getStoresList()
    }


    // 区分详情接口
    const getSellDetailUrl = () => {
        let type = state.tab.value.id
        if (type == 'store') {
            return config.REPORT_SELL_SHOP  // 门店
        } else if (type == 'product') {
            return config.REPORT_SELL_GOODS // 产品
        } else if (type == 'service') {
            return config.REPORT_SELL_GOODS // 服务 
        } else if (type == 'reserva') {
            return config.REPORT_BOOK_CUSTOMER // 预约
        } else if (type == 'customer') {
            return config.REPORT_SELL_CUSTOM // 客户
        } else if (type == 'member') {
            return config.REPORT_SELL_STAFF // 成员
        }
    }

    // 获取销售情况
    const getStoreSellLsData = async () => {
        let type = state.tab.value.id
        let url = getSellDetailUrl()
        let params = {
            ...state.store_query_detail.value,
        }
        if (type == 'service') {
            params.is_yy = '1'
        }
        let res = await Vue.prototype.$api({ url: url, data: params });
        if (res.status == 1) {
            let result = res.data
            let result_ls = []
            if (type == 'product') {
                result_ls = result?.data || []
            } else if (type == 'customer') {
                result_ls = result?.goods_ls || []
            } else if (type == 'service') {
                result_ls = result?.data || []
            } else {
                result_ls = result?.data_ls || []
                state.shop_info.value = { ...state.shop_info.value || {}, ...result?.shop_info || {} }
            }
            if (result_ls && result_ls?.length) {
                const existingIds = new Set(state.store_list.value.map(item => item.id));
                const uniqueNewData = result_ls.filter(item => !existingIds.has(item.id));
                state.store_list.value = state.store_list.value.concat(uniqueNewData);
                state.store_detail_hasMore.value = (result_ls && result_ls?.length) >= PAGE_SIZE;
            } else {
                state.store_detail_hasMore.value = true
            }
            state.store_count.value = result?.count || {}
        }
    }

    //  -----------------------  end  ---------------------------

    return {
        ...state,
        getStoresList,
        storeLoadMoreData,
        getStoreSellLsData,
        resetStoreQuery,
    }
} 